package com.nus.services;

import com.nus.beans.User;
import com.nus.beans.UserType;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.StringTokenizer;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/15/12
 * Time: 11:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class EncodingService {
    private Logger logger = Logger.getLogger(this.getClass());

    public static void main(String[] args) {
        EncodingService es = new EncodingService();
        System.out.println(es.encode("sys"));
        User user = new User();
        user.setUserId(43);
        user.setUserType(UserType.HR_MGR);
        user.setPassword("b4c56ee8d2854166dec66644f541b85247105b2c");
        System.out.println("user name = " + es.getDBUserName(user));
        System.out.println("password = " + es.getDBPassword(user));
    }

    public String encode(String clearTextString) {
        MessageDigest cript = null;
        String encodedString = null;
        try {
            cript = MessageDigest.getInstance("SHA-1");
            cript.reset();
            cript.update(clearTextString.getBytes("utf8"));
            encodedString = toHexString(cript.digest());
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        }
        return encodedString;
    }

    private String toHexString(byte[] buf) {
        char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};

        StringBuffer strBuf = new StringBuffer(buf.length * 2);
        for (int i = 0; i < buf.length; i++) {
            strBuf.append(hexChar[(buf[i] & 0xf0) >>> 4]);
            strBuf.append(hexChar[buf[i] & 0x0f]);
        }
        return strBuf.toString();
    }

    public String getDBPassword(User user) {
        return "x" + user.getPassword().substring(0,7);
    }

    public String getDBUserName(User user){
        StringBuilder builder = new StringBuilder();
        ConversionService conversionService = new ConversionService();
        int userTypeDB = conversionService.getUserType(user.getUserType());
        builder.append("X").append(String.format("%05d", user.getUserId())).append(String.format("%02d", userTypeDB));
        return builder.toString();
    }

}
